package postpic.app;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

import org.json.JSONException;
import org.json.JSONObject;

import postpic.app.io.ClientIO;
import postpic.domain.User;
import postpic.domain.action.Action;
import postpic.domain.session.Request;
import postpic.domain.session.Response;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.EditText;

public class RegisterActivity extends Activity implements OnClickListener {

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
	    super.onCreate(savedInstanceState);
	    setContentView(R.layout.register);
	}
	
	public void alertbox(String mymessage)
	   {
	   new AlertDialog.Builder(this)
	      .setMessage(mymessage)
	      .setTitle("")
	      .setCancelable(true)
	      .setNeutralButton("Ok",
	         new DialogInterface.OnClickListener() {
	         public void onClick(DialogInterface dialog, int whichButton){}
	         })
	      .show();
	   }

	@Override
	public void onClick(View v) {
		switch(v.getId()) {
		case R.id.registerSubmitButton:
			String firstName   = ((EditText)findViewById(R.id.firstNameBox)).getText().toString();
			String lastName   = ((EditText)findViewById(R.id.lastNameBox)).getText().toString();
			String email   = ((EditText)findViewById(R.id.emailBox)).getText().toString();
			String password   = ((EditText)findViewById(R.id.passwordRegisterBox)).getText().toString();
			
			JSONObject registerObject = new JSONObject();
			User user = null;
			
			registerObject.put("email", email);
			registerObject.put("firstName", firstName);
			registerObject.put("lastName", lastName);
			registerObject.put("password", password);
			
			Request request = new Request(Action.REGISTER, registerObject);
			ClientIO.sendRequest(request);
			Response response = ClientIO.getResponse();
			if (response.isSuccessful()) {
				user = new User();
				user.populateFromJSON(response.getJSON());
				ClientIO.USER = user;
				Intent myIntent = new Intent(v.getContext(), UserProfile.class);
			    v.getContext().startActivity(myIntent);
			}
			break;
		
		}
	}

}
